package com.controller;

import com.anno.BackLogin;
import com.anno.FrontLogin;
import com.controller.base.BaseController;
import com.controller.base.BaseFrontController;
import com.controller.base.Response;
import com.model.BackUser;
import com.model.FrontUser;
import com.service.FrontUserService;
import com.utils.from.FrontUserForm;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/frontUser")
public class FrontController extends BaseFrontController {

    @Autowired
    private FrontUserService frontUserService;

    @PostMapping("/register")
    public Response register(@Valid FrontUser from) {
        ModelMapper mapper = new ModelMapper();
        FrontUser user = mapper.map(from, FrontUser.class);
        if(frontUserService.checkExists(user)) {
            return fail("用户已存在");
        }
        boolean result = frontUserService.register(user);
        return result ? success("注册成功") : fail("注册失败");
    }

    @PostMapping("/login")
    public Response login(@Valid FrontUserForm from, HttpSession session) {
        // 验证username
        FrontUser user = frontUserService.getByUsername(from.getUsername());
        if(user == null) return fail("该用户不存在");
        // 验证password
        boolean passwordFlag = frontUserService.checkPasswordByUser(from.getPassword(), user);
        if(!passwordFlag) return fail("密码错误");
        // 缓存到session
        session.setAttribute("front_user", user);
        boolean updateFlag = frontUserService.updateLoginTime(user, LocalDateTime.now());
        if (!updateFlag) return fail("登录失败!");
        return success();
    }

    @FrontLogin
    @PostMapping("/logout")
    public Response logout() {
        removeUserSession();
        return success();
    }

    @PostMapping("/checkSession")
    public Response<FrontUser> getUser(HttpSession session) {
        FrontUser user = (FrontUser) session.getAttribute("front_user");
        if(user == null) return fail();
        user.setPassword("").setRegisterTime(null).setLoginTime(null);
        return success(user);
    }

    @BackLogin
    @PostMapping("/list")
    public Response<List<FrontUser>> list() {
        List<FrontUser> users = frontUserService.findAll();
        users.forEach((user -> {
            user.setPassword(null);
        }));
        return success(users);
    }
}
